const { getUserInfo } = require('../service/user.service')
const { getNum } = require('../utils/mailAotu')
const userValidator = async (ctx, next) => {
    const { userEmail, password } = ctx.request.body
    if (!userEmail || !password) {
        console.error('邮箱或密码为空', ctx.request.body)
        // ctx.status = 400
        ctx.body = {
            code: '10001',
            message: '邮箱或密码为空',
            data: ''
        }
        return
    }
    await next()
}

const verifyUser = async (ctx, next) => {
    const { userEmail } = ctx.request.body
    if (await getUserInfo({ userEmail })) {
        // ctx.status = 409
        ctx.body = {
            code: '10002',
            message: '您已经注册过啦',
            data: '',
        }
        return
    }
    await next()
}

const verifyEcode = async (ctx, next) => {
    const { verificationCode } = ctx.request.body
    const num = getNum()
    if (verificationCode !== num) {
        // ctx.status = 400
        ctx.body = {
            code: '10003',
            message: '邮箱验证码错误',
            data: '',
        }
        return
    }
    await next()
}

const verificationLogin = async (ctx, next) => {
    const { userEmail, password } = ctx.request.body
    const res = await getUserInfo({ userEmail })
    if (!res) {
        ctx.body = {
            code: '10004',
            message: '您还没有注册' + userEmail,
            data: '',
        }
        return
    }
    if(res.password !== password){
        ctx.body = {
            code: '10005',
            message: '账号或密码错误',
            data: '',
        }
        return
    }
    await next()
}
module.exports = {
    userValidator,
    verifyUser,
    verifyEcode,
    verificationLogin
}